<template>
  <el-dialog title="拍照" :visible.sync="visible" width="600px"
             append-to-body
             :close-on-click-modal="false"
             @close="close">
    <div class="camera-container">
      <canvas :class="{took}" id="canvas" ref="canvasRef" width="500px" height="500px" />
      <video id="cameraVideo" ref="videoRef" width="500px" height="500px" autoplay="autoplay" muted></video>
    </div>
    <div class="actions">
      <template v-if="took">
        <el-button @click="took = false">重新拍摄</el-button>
        <el-button type="primary" @click="confirm">确认</el-button>
      </template>
      <el-button v-else type="primary"
                 @click="takePhoto">拍摄照片</el-button>
    </div>
  </el-dialog>
</template>

<script>
export default {
  name: 'AmCameraModal',
  data() {
    return {
      visible: false,
      took: false,
    }
  },
  methods: {
    dataURItoBlob (dataURI) { // base64转buffer
      const byteString = atob(dataURI.split(',')[1])
      const mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]
      const ab = new ArrayBuffer(byteString.length)
      const ia = new Uint8Array(ab)
      for (let i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i)
      }
      return new Blob([ab], { type: mimeString })
    },
    confirm() {
      const canvas = document.getElementById("canvas");
      const dataUrl = canvas.toDataURL('images/jpg')
      const blob = this.dataURItoBlob(dataUrl);
      this.$emit('confirm', blob)
      this.closeCamera()
    },
    takePhoto() {
      //获得Canvas对象
      let video = document.getElementById('cameraVideo');
      let canvas = document.getElementById("canvas");
      let ctx = canvas.getContext('2d');
      //绘图
      ctx.drawImage(video, 0, 0, 500, 500);
      this.took = true
    },
    initCamera() {
      this.$nextTick(() => {
        //获得video摄像头区域
        // let video = this.$refs.videoRef.$el;
        let video = document.getElementById('cameraVideo');
        //返回的Promise对象
        let promise = navigator.mediaDevices.getUserMedia({
          //参数
          video: {width: 500, height: 500},
          audio: true
        });
        promise.then(function (MediaStream) {
          video.srcObject = MediaStream;
          video.play();
        });
      })
    },
    closeCamera() {
      let video = document.getElementById('cameraVideo');
      const stream = video.srcObject;
      const tracks = stream.getTracks();
      tracks.forEach(function(track) {
        track.stop();  //停止视频流
      });
    },
    open() {
      this.visible = true
      this.initCamera()
    },
    close() {
      this.closeCamera();
      this.visible = false
    }
  }
}
</script>

<style lang="scss">
.camera-container{
  width: 100%;
  height: 500px;
  position: relative;
  #cameraVideo{
    position: absolute;
    top: 0;
    left: 50%;
    transform: translateX(-50%);
    z-index: 1;
  }
  #canvas{
    position: absolute;
    top: 0;
    left: 50%;
    transform: translateX(-50%);
    visibility: hidden;
    z-index: 2;
    &.took{
      visibility: visible;
    }
  }
}
.actions{
  padding-top: 10px;
  display: flex;
  justify-content: center;
}
</style>
